package com.deliveryservicesystem.service.crud.impl;

import com.deliveryservicesystem.app.exceptions.NonexistentEntityException;
import com.deliveryservicesystem.app.exceptions.PreexistingEntityException;
import com.deliveryservicesystem.dataaccess.PersistenceDbManager;
import com.deliveryservicesystem.model.Delivery;
import com.deliveryservicesystem.model.Driver;
import com.deliveryservicesystem.model.Route;
import com.deliveryservicesystem.model.Subscription;
import com.deliveryservicesystem.service.crud.DeliveryCrudService;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * File Name: DeliveryCrudServiceImpl.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.service.crud.impl
 * Author: Lance
 * Date: Jun 20, 2012
 * Editor:
 */
public class DeliveryCrudServiceImpl implements DeliveryCrudService
{

    private static final long serialVersionUID = 1L;
    private EntityManagerFactory emf = null;

    /**
     * Create the new CRUD service. Internally setting the EntityManagerFactory
     * using database details from database properties
     */
    public DeliveryCrudServiceImpl()
    {
        PersistenceDbManager persistenceManager = PersistenceDbManager.getInstance();
        this.emf = persistenceManager.getEntityManagerFactory();
    }

    @Override
    public EntityManager getEntityManager()
    {
        return emf.createEntityManager();
    }

    @Override
    public void create(Delivery delivery) throws PreexistingEntityException, Exception
    {
        if (delivery.getRouteList() == null)
        {
            delivery.setRouteList(new ArrayList<Route>());
        }
        if (delivery.getSubscriptionList() == null)
        {
            delivery.setSubscriptionList(new ArrayList<Subscription>());
        }
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Driver driverNo = delivery.getDriverNo();
            if (driverNo != null)
            {
                driverNo = em.getReference(driverNo.getClass(), driverNo.getDriverNo());
                delivery.setDriverNo(driverNo);
            }
            List<Route> attachedRouteList = new ArrayList<>();
            for (Route routeListRouteToAttach : delivery.getRouteList())
            {
                routeListRouteToAttach = em.getReference(routeListRouteToAttach.getClass(), routeListRouteToAttach.getRouteNo());
                attachedRouteList.add(routeListRouteToAttach);
            }
            delivery.setRouteList(attachedRouteList);
            List<Subscription> attachedSubscriptionList = new ArrayList<>();
            for (Subscription subscriptionListSubscriptionToAttach : delivery.getSubscriptionList())
            {
                subscriptionListSubscriptionToAttach = em.getReference(subscriptionListSubscriptionToAttach.getClass(), subscriptionListSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionList.add(subscriptionListSubscriptionToAttach);
            }
            delivery.setSubscriptionList(attachedSubscriptionList);
            em.persist(delivery);
            if (driverNo != null)
            {
                driverNo.getDeliveryList().add(delivery);
                driverNo = em.merge(driverNo);
            }
            for (Route routeListRoute : delivery.getRouteList())
            {
                Delivery oldDeliveryNoOfRouteListRoute = routeListRoute.getDeliveryNo();
                routeListRoute.setDeliveryNo(delivery);
                routeListRoute = em.merge(routeListRoute);
                if (oldDeliveryNoOfRouteListRoute != null)
                {
                    oldDeliveryNoOfRouteListRoute.getRouteList().remove(routeListRoute);
                    oldDeliveryNoOfRouteListRoute = em.merge(oldDeliveryNoOfRouteListRoute);
                }
            }
            for (Subscription subscriptionListSubscription : delivery.getSubscriptionList())
            {
                Delivery oldDeliveryNoOfSubscriptionListSubscription = subscriptionListSubscription.getDeliveryNo();
                subscriptionListSubscription.setDeliveryNo(delivery);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
                if (oldDeliveryNoOfSubscriptionListSubscription != null)
                {
                    oldDeliveryNoOfSubscriptionListSubscription.getSubscriptionList().remove(subscriptionListSubscription);
                    oldDeliveryNoOfSubscriptionListSubscription = em.merge(oldDeliveryNoOfSubscriptionListSubscription);
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            if (findById(delivery.getDeliveryNo()) != null)
            {
                throw new PreexistingEntityException("Delivery " + delivery + " already exists.", ex);
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void edit(Delivery delivery) throws NonexistentEntityException, Exception
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Delivery persistentDelivery = em.find(Delivery.class, delivery.getDeliveryNo());
            Driver driverNoOld = persistentDelivery.getDriverNo();
            Driver driverNoNew = delivery.getDriverNo();
            List<Route> routeListOld = persistentDelivery.getRouteList();
            List<Route> routeListNew = delivery.getRouteList();
            List<Subscription> subscriptionListOld = persistentDelivery.getSubscriptionList();
            List<Subscription> subscriptionListNew = delivery.getSubscriptionList();
            if (driverNoNew != null)
            {
                driverNoNew = em.getReference(driverNoNew.getClass(), driverNoNew.getDriverNo());
                delivery.setDriverNo(driverNoNew);
            }
            List<Route> attachedRouteListNew = new ArrayList<>();
            for (Route routeListNewRouteToAttach : routeListNew)
            {
                routeListNewRouteToAttach = em.getReference(routeListNewRouteToAttach.getClass(), routeListNewRouteToAttach.getRouteNo());
                attachedRouteListNew.add(routeListNewRouteToAttach);
            }
            routeListNew = attachedRouteListNew;
            delivery.setRouteList(routeListNew);
            List<Subscription> attachedSubscriptionListNew = new ArrayList<>();
            for (Subscription subscriptionListNewSubscriptionToAttach : subscriptionListNew)
            {
                subscriptionListNewSubscriptionToAttach = em.getReference(subscriptionListNewSubscriptionToAttach.getClass(), subscriptionListNewSubscriptionToAttach.getSubscriptionNo());
                attachedSubscriptionListNew.add(subscriptionListNewSubscriptionToAttach);
            }
            subscriptionListNew = attachedSubscriptionListNew;
            delivery.setSubscriptionList(subscriptionListNew);
            delivery = em.merge(delivery);
            if (driverNoOld != null && !driverNoOld.equals(driverNoNew))
            {
                driverNoOld.getDeliveryList().remove(delivery);
                driverNoOld = em.merge(driverNoOld);
            }
            if (driverNoNew != null && !driverNoNew.equals(driverNoOld))
            {
                driverNoNew.getDeliveryList().add(delivery);
                driverNoNew = em.merge(driverNoNew);
            }
            for (Route routeListOldRoute : routeListOld)
            {
                if (!routeListNew.contains(routeListOldRoute))
                {
                    routeListOldRoute.setDeliveryNo(null);
                    routeListOldRoute = em.merge(routeListOldRoute);
                }
            }
            for (Route routeListNewRoute : routeListNew)
            {
                if (!routeListOld.contains(routeListNewRoute))
                {
                    Delivery oldDeliveryNoOfRouteListNewRoute = routeListNewRoute.getDeliveryNo();
                    routeListNewRoute.setDeliveryNo(delivery);
                    routeListNewRoute = em.merge(routeListNewRoute);
                    if (oldDeliveryNoOfRouteListNewRoute != null && !oldDeliveryNoOfRouteListNewRoute.equals(delivery))
                    {
                        oldDeliveryNoOfRouteListNewRoute.getRouteList().remove(routeListNewRoute);
                        oldDeliveryNoOfRouteListNewRoute = em.merge(oldDeliveryNoOfRouteListNewRoute);
                    }
                }
            }
            for (Subscription subscriptionListOldSubscription : subscriptionListOld)
            {
                if (!subscriptionListNew.contains(subscriptionListOldSubscription))
                {
                    subscriptionListOldSubscription.setDeliveryNo(null);
                    subscriptionListOldSubscription = em.merge(subscriptionListOldSubscription);
                }
            }
            for (Subscription subscriptionListNewSubscription : subscriptionListNew)
            {
                if (!subscriptionListOld.contains(subscriptionListNewSubscription))
                {
                    Delivery oldDeliveryNoOfSubscriptionListNewSubscription = subscriptionListNewSubscription.getDeliveryNo();
                    subscriptionListNewSubscription.setDeliveryNo(delivery);
                    subscriptionListNewSubscription = em.merge(subscriptionListNewSubscription);
                    if (oldDeliveryNoOfSubscriptionListNewSubscription != null && !oldDeliveryNoOfSubscriptionListNewSubscription.equals(delivery))
                    {
                        oldDeliveryNoOfSubscriptionListNewSubscription.getSubscriptionList().remove(subscriptionListNewSubscription);
                        oldDeliveryNoOfSubscriptionListNewSubscription = em.merge(oldDeliveryNoOfSubscriptionListNewSubscription);
                    }
                }
            }
            em.getTransaction().commit();
        }
        catch (Exception ex)
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0)
            {
                Integer id = delivery.getDeliveryNo();
                if (findById(id) == null)
                {
                    throw new NonexistentEntityException("The delivery with id " + id + " no longer exists.");
                }
            }
            throw ex;
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException
    {
        EntityManager em = null;
        try
        {
            em = getEntityManager();
            em.getTransaction().begin();
            Delivery delivery;
            try
            {
                delivery = em.getReference(Delivery.class, id);
                delivery.getDeliveryNo();
            }
            catch (EntityNotFoundException enfe)
            {
                throw new NonexistentEntityException("The delivery with id " + id + " no longer exists.", enfe);
            }
            Driver driverNo = delivery.getDriverNo();
            if (driverNo != null)
            {
                driverNo.getDeliveryList().remove(delivery);
                driverNo = em.merge(driverNo);
            }
            List<Route> routeList = delivery.getRouteList();
            for (Route routeListRoute : routeList)
            {
                routeListRoute.setDeliveryNo(null);
                routeListRoute = em.merge(routeListRoute);
            }
            List<Subscription> subscriptionList = delivery.getSubscriptionList();
            for (Subscription subscriptionListSubscription : subscriptionList)
            {
                subscriptionListSubscription.setDeliveryNo(null);
                subscriptionListSubscription = em.merge(subscriptionListSubscription);
            }
            em.remove(delivery);
            em.getTransaction().commit();
        }
        finally
        {
            if (em != null)
            {
                em.close();
            }
        }
    }

    @Override
    public List<Delivery> findEntities()
    {
        return findDeliveryEntities(true, -1, -1);
    }

    @Override
    public List<Delivery> findEntities(int maxResults, int firstResult)
    {
        return findDeliveryEntities(false, maxResults, firstResult);
    }

    private List<Delivery> findDeliveryEntities(boolean all, int maxResults, int firstResult)
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Delivery.class));
            Query q = em.createQuery(cq);
            if (!all)
            {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public Delivery findById(Integer id)
    {
        EntityManager em = getEntityManager();
        try
        {
            return em.find(Delivery.class, id);
        }
        finally
        {
            em.close();
        }
    }

    @Override
    public int count()
    {
        EntityManager em = getEntityManager();
        try
        {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Delivery> rt = cq.from(Delivery.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        }
        finally
        {
            em.close();
        }
    }
}
